package com.autorun.server.config;

import com.autorun.server.entity.User;
import com.autorun.server.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 数据初始化器
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化数据...");

        // 检查是否已有管理员用户
        Integer adminCount = userMapper.countByUsernameAndIsAdmin("admin", true);
        if (adminCount == 0) {
            log.info("未找到管理员用户，创建默认管理员...");
            
            // 创建默认管理员
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("123456"));
            admin.setNumber(10);
            admin.setIsAdmin(true);
            admin.setCreateTime(LocalDateTime.now());
            admin.setUpdateTime(LocalDateTime.now());
            
            userMapper.insert(admin);
            log.info("默认管理员创建成功 - 用户名: admin, 密码: 123456");
        } else {
            log.info("管理员用户已存在，跳过创建");
        }

        log.info("数据初始化完成");
    }
}